package com.danbay.framework.utils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author SJG
 *         2017/11/20.
 */
@Slf4j
public class JsonUtils {

    public static <T> T parse(ObjectMapper objectMapper, String json, Type dest){
        try {
            //泛型的参数类型
            if (dest instanceof ParameterizedType) {
                ParameterizedTypeImpl ptype = (ParameterizedTypeImpl) dest;
                Type[] actTypes = ptype.getActualTypeArguments();
                Class[] actCls = new Class[actTypes.length];
                for (int i = 0; i < actTypes.length; i++) {
                    actCls[i] = (Class) actTypes[i];
                }
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ptype.getRawType(), actCls);
                return objectMapper.readValue(json, javaType);
            } else {
                //其它类型
                return objectMapper.readValue(json, (Class<T>) dest);
            }
        }catch (Exception e){
            log.error("json parse error",e);
            return null;
        }
    }
}
